package com.sisSaude.utils;

import java.util.Iterator;
import java.util.Vector;

/**
 * Factory de SQL's 
 * @author marciel.ramos
 *
 */
public class SqlFactory {
	
	/** Retorna a SQL de INSERT 
	 * @param tableName - nome da tabela
	 * **/
	public static String getSqlInsert(String tableName) {
		Vector<String> columns = getColumns(tableName); 
		Iterator<String> i = columns.iterator();
		String s = null;
		String result = "INSERT INTO " + tableName + " (";
		while (i.hasNext()) {
			  s = (String) i.next();
			  if   (i.hasNext())
				   result += s + ",";
			  else result += s + ")";
		}
		result += " VALUES (?" + MyString.repeat(",?", columns.size()-1) + ")";
		return result;
	}
	
	/** Retorna a SQL de UPDATE 
	 * @param tableName - nome da tabela
	 * @param fieldConditional - campo condicional para efetuar o UPDATE
	 * **/
	public static String getSqlUpdate(String tableName, String fieldConditional) {
		Vector<String> columns = getColumns(tableName); 
		Iterator<String> i = columns.iterator();
		String s = null;
		String result = "UPDATE " + tableName + " SET ";
		while (i.hasNext()) {
			  s = (String) i.next();
			  if (!s.toUpperCase().equals(fieldConditional.toUpperCase())  && !(tableName + "." + s).toUpperCase().equals(fieldConditional.toUpperCase())) {
				  result += s + " = ? ";
				  if   (i.hasNext())
					   result += ",";
			  }
		}
		result += " WHERE " + fieldConditional + " = ? ";
		return result;
	}	
	
	/** Retorna a SQL de DELETE 
	 * @param tableName - nome da tabela
	 * @param fieldConditional - campo condicional para efetuar o DELETE
	 * **/
	public static String getSqlDelete(String tableName, String fieldConditional) {
		return " DELETE FROM " + tableName + " WHERE " + fieldConditional + " = ?";
	}		
	
	/** Vetor com as columas de uma tabela 
	 * @param tableName - nome da tabela
	 * **/
	private static Vector<String> getColumns(String tableName) {
		DataProvider dataProvider = new DataProvider();
		Vector<String> result = new Vector<String>();
		String sql = "";
		sql += " DESC " + tableName.toUpperCase() ;
		dataProvider.select(sql, null);
		try {
			while (dataProvider.next()) {
				result.add(dataProvider.getResultSet().getString(1));
			}
		}catch (Exception e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
			dataProvider.close();
		};
		dataProvider.close();
		return result;
	}
}
